package com.fjp.heartguard.app.weight

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

class CircleImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val borderPaint = Paint()
    private val bitmapShader = BitmapShader(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
    private val circlePaint = Paint()
    private var radius = 0f
    private var borderWidth = 4f // 边框宽度，单位为像素

    init {
        // 初始化边框画笔
        borderPaint.color = Color.WHITE
        borderPaint.style = Paint.Style.STROKE
        borderPaint.strokeWidth = borderWidth
        borderPaint.isAntiAlias = true

        // 初始化圆形画笔
        circlePaint.isAntiAlias = true
        circlePaint.shader = bitmapShader
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val size = Math.min(measuredWidth, measuredHeight)
        setMeasuredDimension(size, size)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        radius = (Math.min(w, h) / 2).toFloat()
    }

    override fun onDraw(canvas: Canvas) {
        val drawable = drawable
        if (drawable == null) {
            return
        }
        val bitmap = drawableToBitmap(drawable)
        setupShader(bitmap)
        // 绘制圆形图片
        canvas.drawCircle(width / 2f, height / 2f, radius - borderWidth / 2, circlePaint)
        // 绘制圆形边框
        canvas.drawCircle(width / 2f, height / 2f, radius - borderWidth / 2, borderPaint)
    }

    private fun drawableToBitmap(drawable: Drawable): Bitmap {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }
        val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bitmap
    }

    private fun setupShader(bitmap: Bitmap) {
        val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        matrix.setScale(width / bitmap.width.toFloat(), height / bitmap.height.toFloat())
        bitmapShader?.setLocalMatrix(matrix)
        circlePaint.shader = bitmapShader
    }
}